package com.ok.es.listener;

import cn.hutool.json.JSONUtil;
import com.ok.common.domain.po.CartoonDoc;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName CartoonEsListener
 * @Description 消息队列数据同步更新
 * @Author hw
 * @Date 2024/5/14 20:44
 */
@Slf4j
@Component
public class CartoonEsListener {
    @Autowired
    private RestHighLevelClient client;
    /*
    添加漫画文档
     */
    @RabbitListener(queues = "cartoon_add_queue")
    public void listenerCartoonAdd(CartoonDoc cartoonDoc) throws IOException {
        log.info("es接收漫画信息："+cartoonDoc);

        //将cartoonDoc转换为JSON文档
        String doc = JSONUtil.toJsonStr(cartoonDoc);
        IndexRequest request = new IndexRequest("cartoon").id(cartoonDoc.getId());

        //准备JSON文档
        request.source(doc, XContentType.JSON);
        //发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    /*
    删除漫画
     */
    @RabbitListener(queues = "cartoon_rm_queue")
    public void rm(Integer id) throws IOException {
        log.info("漫画es--id:{}",id);
        // 1.准备Request，两个参数，第一个是索引库名，第二个是文档id
        DeleteRequest request = new DeleteRequest("cartoon", String.valueOf(id));
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }
}
